#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
#include <stack>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> v;
        TreeNode* pcur = root;
        while (pcur || !st.empty())
        {
            while (pcur)
            {
                st.push(pcur);
                v.push_back(pcur->val);
                pcur = pcur->left;
            }
            pcur = st.top()->right;
            st.pop();
        }
        return v;
    }
};